package com.nexus.plugin.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.nexus.core.properties.ExternalPropertySourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * @Date 2025/7/29 17:18
 * @Author luzhengning
 **/
@Configuration
@org.springframework.context.annotation.PropertySource(
        name = "json.properties",
        value = "classpath*:json-pro.properties",encoding = "UTF8",
        factory = ExternalPropertySourceFactory.class,
        ignoreResourceNotFound = true
)
public class JacksonConfig {

    // 统一日期时间格式
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        // 1. 配置Java8日期时间模块
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
        // 注册LocalDateTime的序列化器与反序列化器
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        objectMapper.registerModule(javaTimeModule);
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));

        // 2. 其他核心配置
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // 空对象不报错
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 禁用时间戳格式
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 忽略未知字段
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // 美化JSON输出
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 忽略null字段

        // 3. 处理枚举类型（确保序列化为name）
        objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, false);

        // 4. 注册其他模块（如自定义模块）
        objectMapper.registerModule(serializerAndDeserializerModule());

        return objectMapper;
    }

    /**
     * 自定义序列化/反序列化模块
     *
     * @return SimpleModule
     */
    public SimpleModule serializerAndDeserializerModule() {
        SimpleModule module = new SimpleModule();


        return module;
    }


}